package com.myaihui.controller;

import com.myaihui.domain.*;
import com.myaihui.foundation.constant.SysConst;
import com.myaihui.foundation.model.Pager;
import com.myaihui.foundation.msg.MsgDefinition;
import com.myaihui.foundation.msg.ResultMsg;
import com.myaihui.foundation.query.UserQuery;
import com.myaihui.service.MarketService;
import com.myaihui.service.PropertyMgrService;
import com.myaihui.service.RoleService;
import com.myaihui.service.SysUserService;
import com.myaihui.util.EncryptUtil;
import com.myaihui.util.LoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by sun on 2018/7/3.
 *
 * @author sunfuchang03@126.com
 * @version 1.0
 * @since 1.0
 */
@RequestMapping("/admins")
@Controller
public class AdminController {
    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Static fields/constants/initializer
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    private static Logger log = LoggerFactory.getLogger(AdminController.class);

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Instance fields
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MarketService marketService;
    @Autowired
    private PropertyMgrService propertyMgrService;

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Constructors
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */



    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Public Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @RequestMapping("/home")
    public String home(Model model) {
        return "admin/home";
    }

    @RequestMapping("/{userId}/edit")
    public String edit(@PathVariable("userId") String userId, Model model) {
        SysUser sysUser = sysUserService.getById(userId);
        model.addAttribute("user", sysUser);
        return "admin/edit";
    }

    @PostMapping("/exists")
    @ResponseBody
    public ResultMsg checkNameExists(String userId, String name) {
        if (!StringUtils.hasLength(name)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        boolean exists = false;
        if (StringUtils.hasLength(userId)) {
            exists = sysUserService.findByUsernameExcludeId(name, userId) != null;
        } else {
            exists = sysUserService.findByUsername(name) != null;
        }
        return ResultMsg.success(exists);
    }

    @RequestMapping("/{userId}/roles")
    public String userRole(@PathVariable("userId") String userId, Model model) {
        SysUser sysUser = sysUserService.getById(userId);
        List<Role> roles = roleService.findByType(sysUser.getType());
        List<Role> userRoles = roleService.findByUserId(userId);
        for (Role role : roles) {
            for (Role userRole : userRoles) {
                if (userRole.getId().equals(role.getId())) {
                    role.setChecked(true);
                    break;
                }
            }
            List<Resource> resources = roleService.findResourcesByRoleId(role.getId());
            role.setResources(resources);
        }
        model.addAttribute("user", sysUser);
        model.addAttribute("roles", roles);
        return "admin/role";
    }

    @RequestMapping("/{userId}/enable")
    @ResponseBody
    public ResultMsg enable(@PathVariable("userId") String userId) {
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null) {
            return ResultMsg.error(MsgDefinition.UNKOWN_ERROR, "用户不存在");
        }
        if (SysConst.UserState.ENABLE != sysUser.getState()) {
            sysUser.setState(SysConst.UserState.ENABLE);
            sysUserService.update(sysUser);
        }
        return ResultMsg.success(true);
    }

    @RequestMapping("/{userId}/disable")
    @ResponseBody
    public ResultMsg disable(@PathVariable("userId") String userId) {
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null) {
            return ResultMsg.error(MsgDefinition.UNKOWN_ERROR, "用户不存在");
        }
        if (SysConst.UserState.DISABLE != sysUser.getState()) {
            sysUser.setState(SysConst.UserState.DISABLE);
            sysUserService.update(sysUser);
        }
        return ResultMsg.success(true);
    }

    @RequestMapping("/page")
    @ResponseBody
    public ResultMsg pageQuery(UserQuery userQuery) {
        userQuery.setAdmin(true);
        Pager<SysUser> users = sysUserService.pageQuery(userQuery);
        if (users != null) {
            for (SysUser user : users.getAaData()) {
                Integer type = user.getType();
                String subjectId = user.getPlatformId();
                if (type != null && StringUtils.hasLength(subjectId)) {
                    if (SysConst.SubjectType.PROPERTY == type) {
                        PropertyMgr pm = propertyMgrService.get(subjectId);
                        if (pm != null) {
                            user.setSubjectName(pm.getName());
                        }
                    } else if (SysConst.SubjectType.MALL == type) {
                        Market market = marketService.get(subjectId);
                        if (market != null) {
                            user.setSubjectName(market.getName());
                        }
                    }
                }
            }
        }
        return ResultMsg.success(users);
    }

    @RequestMapping("/{userId}/delete")
    @ResponseBody
    public ResultMsg delete(@PathVariable String userId) {
        SysUser sysUser = sysUserService.getById(userId);
        sysUser.setDeleted(true);
        sysUserService.update(sysUser);
        return ResultMsg.success(true);
    }

    @RequestMapping("/save")
    @ResponseBody
    public ResultMsg saveUser(SysUser sysUser) {
        String userId = sysUser.getId();
        SysUser loginUser = LoginUtil.loginUser();
        if (StringUtils.hasLength(userId)) {
            SysUser destUser = sysUserService.getById(userId);
            destUser.setRealName(sysUser.getRealName());
            destUser.setMobile(sysUser.getMobile());
            destUser.setGender(sysUser.getGender());
            sysUserService.update(destUser);
        } else {
            sysUser.setPassword(EncryptUtil.passwordEncrypt(sysUser.getUsername(), "123456"));
            sysUser.setCreated(new Date());
            sysUser.setCreateUserId(loginUser.getId());
            sysUser.setPlatformId(loginUser.getPlatformId());
            sysUser.setState(SysConst.UserState.ENABLE);
            sysUser.setPlatformType(
                    loginUser.getPlatformType() == SysConst.SubjectType.SUPER_ADMIN
                            ? SysConst.SubjectType.PLATFORM : loginUser.getPlatformType()
            );
            sysUserService.add(sysUser);
        }
        return ResultMsg.success(true);
    }

    @RequestMapping("/{userId}/role/save")
    @ResponseBody
    public ResultMsg saveRole(@PathVariable("userId") String userId, String roleIds) {
        if (!StringUtils.hasLength(roleIds)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        String[] roleIdsArray = roleIds.split(",");
        roleService.saveUserRoles(userId, Arrays.asList(roleIdsArray));
        return ResultMsg.success(true);
    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Private Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */


}